package com.douqu.game.configManager;

import com.douqu.game.mergeManager.mergeUtils.DatabaseConfig;
import com.douqu.game.mergeManager.mergeUtils.DatabaseFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author: Bean.
 * Description:
 * Date: 2018/4/26 0026 下午 3:50
 * Huan Yu Copyright (c) 2017 All Rights Reserved.
 */
public class ServerUtils {

    public static void main(String[] args) {
        try{
            StartServer("");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String StartServer(String path)  throws Exception {
        File file = new File(path);
        if(file == null || !file.exists()){
            System.out.println(path + "文件不存在");
            throw new Exception(path + "文件不存在");
        }
        Runtime runtime = Runtime.getRuntime();
        try{
            String bat = "java -jar " + path;
            BufferedReader br = new BufferedReader(new InputStreamReader(runtime.exec(bat).getInputStream()));
            String line = null;
            StringBuffer b = new StringBuffer();
            while ((line = br.readLine()) != null){
                b.append(line + "\n");
            }
            System.out.println(b.toString());
            return b.toString();
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception(path + "执行失败!");
        }
    }

//    public static boolean run_cmd(String strcmd){
//        Runtime rt = Runtime.getRuntime();//返回当前应用程序的Runtime对象
//        Process ps = null;//控制该子进程的执行或获取该子进程的执行
//        try{
//            ps = rt.exec(strcmd);//指示java虚拟机 创建一个子进程 执行制定的可执行程序 并返回该子进程对应的process对象的实例e;
//            ps.waitFor(); //等待子进程 完成后再往下执行
//        }catch(Exception e){
//            e.printStackTrace();
//            return false;
//        }
//
//        int i = ps.exitValue();//接收执行完毕的返回值
//
//        ps.destroy();//销毁子进程
//        ps = null;
//        if(i == 0){
//            System.out.println("执行完成");
//            return true;
//        }else{
//            System.out.println("执行失败");
//            return false;
//        }
//    }

    public static boolean run_cmd(String strcmd){
        try
        {
            final Process process = Runtime.getRuntime().exec(strcmd);
            System.out.println("start run cmd=" + strcmd);

            //处理InputStream的线程
            new Thread()
            {
                @Override
                public void run()
                {
                    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line = null;

                    try
                    {
                        while((line = in.readLine()) != null)
                        {
                            System.out.println("output: " + line);
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                        try
                        {
                            in.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            new Thread()
            {
                @Override
                public void run()
                {
                    BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line = null;

                    try
                    {
                        while((line = err.readLine()) != null)
                        {
                            System.out.println("err: " + line);
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                        try
                        {
                            err.close();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            //process.waitFor();
            System.out.println("finish run cmd=" + strcmd);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public static String createNewServer(String host, String port, String user, String pwd, int serverId, String sqlFilePath)
    {
        if(serverId <= 0)
        {
            return "服务器ID错误";
        }

        File file = new File(sqlFilePath);
        if(!file.exists())
        {
            return "数据库文件不存在 -> " + sqlFilePath;
        }

        if(!file.getName().endsWith(".sql"))
        {
            return "数据库文件不是SQL文件 -> " + sqlFilePath;
        }

        String db = "slg" + serverId;
        DatabaseFactory databaseFactory = new DatabaseFactory(new DatabaseConfig(host, port, db,user, pwd));

        System.out.println("检查数据库是否存在===================");
        boolean dbExist = databaseFactory.isDBExist();
        if(dbExist)
        {
            return "数据库 " + db + " 已经存在,请检查!";
        }

        System.out.println("开始创建数据库=========================" + db);

        DatabaseFactory checkDB = new DatabaseFactory(new DatabaseConfig(host, port, user, pwd));
        int count = checkDB.execute("create database " + db);
        if(count <= 0)
            return "创建数据库出错,请检查!";

        System.out.println("数据库创建成功，现在开始执行SQL====================" + db);

        boolean result = databaseFactory.executeSqlFile(sqlFilePath);
        if(!result)
            return "SQL文件有错";

        System.out.println("SQL文件执行成功=============================");

        return "OK";
    }
}
